<?php
class RM_User_CheckoutFIController extends RM_Controller
{
    /**
     * Form Creation
     */
    public function formAction()
    {
        // get settings
        $configObject = new RM_CheckoutFI();
        $config = $configObject->getSettings()->current();

        // create CheckoutFI service object
        $co=new RM_CheckoutFI_Service((int)$config->merchant_id,$config->security_key); // merchantID and securitykey (normally about 80 chars)

        $reservationDetails = RM_Reservation_Manager::getInstance()->getAllDetails();
        $reservationsModel = new RM_Reservations();
        $unitModel = new RM_Units;
        $lang = RM_Environment::getInstance()->getLocale();

        $bookingref = RM_Reservation_Manager::getInstance()->getReservationID();

        // create the description text
        $description =  $bookingref.": ";
        $count = 1;
        foreach ($reservationDetails as $details){
            $unit = $details->getUnit();
            $period = $details->getPeriod();
            $unit_details = $unitModel->get($unit->getId(), $lang);
            $description .= $this->_translate->_( 'Admin.PayPal.Main', 'Selection')." ".$count."(".$unit_details->name." (".$unit->getId().") ".$period->getStart()." ".$this->_translate->_( 'Admin.PayPal.Main', 'to')." ".$period->getEnd().")";
            $count+=1;
        }

        $chargetotal = $reservationsModel->find($bookingref)->current()->getTotalPrice();

        $chargetotal = $chargetotal*100; // convert to cents

        $userdetails = RM_Reservation_Manager::getInstance()->getUser()->toArray();

        $coData=array();
        $coData["stamp"]=time(); // unique timestamp
        $coData["reference"]=$bookingref;
        $coData["message"]=$description;
        $coData["return"]=RM_Environment::getInstance()->getRouter()->_('CheckoutFI', 'process');
        $coData["amount"]= $chargetotal; // price in cents
        $coData["delivery_date"]=date("Ymd");
        $coData["firstname"]=$userdetails['first_name'];
        $coData["familyname"]=$userdetails['last_name'];
        $coData["address"]=$userdetails['address1'];
        $coData["postcode"]=$userdetails['postcode'];
        $coData["postoffice"]=$userdetails['state'];

        // XML mode with bank buttons
        $return=$co->getCheckoutXML($coData); // get payment button data
        $xml=simplexml_load_string($return);

        $this->view->paylaterlink = $xml->paymentURL;
        $this->view->xml = $xml;
    }

    /**
     * Proccess form
     */
    public function processAction(){

        $this->_withoutView();

        if(!isset($_GET['MAC'])){
            RM_Log::toLog("CheckoutFI: MAC variable not found return aborted!");
            return array(
                'data' => array("success" => false, "paid" => false)
            );
        }

        // get settings
        $configObject = new RM_CheckoutFI();
        $config = $configObject->getSettings()->current();

        // create CheckoutFI service object
        $co=new RM_CheckoutFI_Service((int)$config->merchant_id,$config->security_key); // merchantID and securitykey (normally about 80 chars)

        if($co->validateCheckout($_GET)) {

            if($co->isPaid()) {

                $bookingref = RM_Reservation_Manager::getInstance()->getReservationID();
                // save the reservation
                RM_Log::toLog("Booking ref payment complete, by CheckoutFI: ".$bookingref);

                $reservationsModel = new RM_Reservations();
                $chargetotal = $reservationsModel->find($bookingref)->current()->getTotalPrice();

                $reservation = $reservationsModel->find($bookingref)->current();

                $reservationsModel->confirm($reservation);
                RM_Log::toLog("Confirmed Updated");

                $reservationsModel->inProgressComplete($reservation);
                RM_Log::toLog("InProgress Marker Updated");

                $billingModel = new RM_Billing();
                $billingRow = $billingModel->createRow();
                $billingRow->reservation_id = $bookingref;
                $billingRow->total_paid = $chargetotal;
                $billingID = $billingRow->save();

                RM_Log::toLog("Billing Updated");

                // save the payment information
                $billingPaymentsModel = new RM_BillingPayments();
                $billingPaymentRow = $billingPaymentsModel->createRow();
                $billingPaymentRow->id = $billingID;
                $billingPaymentRow->provider = "CheckoutFI";
                $billingPaymentRow->transaction_id = "N/A";
                $billingPaymentRow->status = "success";
                $billingPaymentRow->total = $chargetotal;
                $billingPaymentRow->transaction_date = Date("Y-m-d");
                $billingPaymentRow->save();

                RM_Log::toLog("Billing Payments Updated");

                RM_Reservation_Manager::getInstance()->setPaymentStatus(RM_Payments_Status::TRANSACTION_END_SUCCESSFULLY);
                $this->_forward('success', 'Payments');
            } else {
                RM_Log::toLog("CheckoutFI: payment not paid");
                RM_Reservation_Manager::getInstance()->resetUser();
		$this->_forward('failed', 'CheckoutFI');
            }

	} else {
            RM_Log::toLog("CheckoutFI: MAC variable not found return aborted!");
            RM_Reservation_Manager::getInstance()->resetUser();
            $this->_forward('failed', 'CheckoutFI');
        }
    }

    public function failedAction(){
        //We need to reset user object accorting to ticket #59 in Trac
        RM_Reservation_Manager::getInstance()->resetUser();
    }

    public function ccFormAction(){

    }
    
    public function cancelAction(){
        //We need to reset user object accorting to ticket #59 in Trac
        RM_Reservation_Manager::getInstance()->resetUser();

        // return a cancelled message
        return array(
            'data' => array('success' => true)
        );
    }

    public function successAction(){

        RM_Reservation_Manager::getInstance()->setPaymentStatus(RM_Payments_Status::TRANSACTION_END_SUCCESSFULLY);
        $this->_forward('success', 'payments');
    }
}